const fs = require("fs");
const path = require("path");
const { sys_model, querySql, sys_model_field, op } = require("../../middleware/baseModel");
const autoFile = require("../service/autoFile");
const funTool = require("../../tool/funTool");
const uuid = require("node-uuid");
module.exports = {
  "POST /sys_model/interface": async (ctx, next) => {
    let row = ctx.getBody();
    const baseModel = require("../../middleware/baseModel");
    let { model_key, map_option } = row;
    let { key, value } = map_option;

    if (baseModel[model_key]) {
      let dataRows = await baseModel[model_key].findAll({ attributes: [key, value] });

      dataRows = dataRows.map((p) => {
        return { key: p[key] + "", value: p[value] };
      });
      return ctx.success(dataRows);
    }

    return ctx.fail("数据模型不存在");
  },

  "GET /sys_model/all": async (ctx, next) => {
    let resList = await sys_model.findAll();

    let resPromise = resList.map(async (row) => {
      let newRow = row.toJSON();

      let isExistTableName = await querySql(`select TABLE_NAME from information_schema.TABLES where TABLE_NAME ="${newRow.key}"`);
      if (isExistTableName && isExistTableName.length > 0) {
        newRow.isTableExist = true;
      } else {
        newRow.isTableExist = false;
      }

      let modelPath = path.join(__dirname, `../model/${newRow.key}.js`);
      let isExistModel = await funTool.isExist(modelPath);
      newRow.isExistModel = isExistModel;

      // 查询模型下所有字段
      let dbColKeys = [];
      let modelRow = await sys_model.findOne({ where: { id: newRow.id } });
      if (modelRow && newRow.isTableExist) {
        let colRows = await querySql(`show columns from  ${modelRow.key}`);
        dbColKeys = colRows.map((p) => p.Field);
      }

      let isDbFielExist = true;
      let model_fields = await sys_model_field.findAll({ where: { model_id: newRow.id } });
      model_fields.forEach((newFielRow) => {
        let = newFielRow.toJSON();
        if (dbColKeys.indexOf(newFielRow.key) === -1) {
          isDbFielExist = false;
        }
      });

      newRow.isDbFielExist = isDbFielExist;

      return newRow;
    });

    let newResList = await Promise.all(resPromise);

    return ctx.success(newResList);
  },

  "GET /sys_model/detail": async (ctx, next) => {
    let id = ctx.get("id");
    let res = await sys_model.findOne({ where: { id } });
    return ctx.success(res);
  },

  "POST /sys_model/add": async (ctx, next) => {
    let row = ctx.getBody();
    let { key, name } = row;
    key = key.trim();

    const res = await sys_model.create({ key, name });

    return ctx.success(res);
  },

  "POST /sys_model/edit": async (ctx, next) => {
    let row = ctx.getBody();
    let { id, key, name } = row;
    key = key.trim();

    const res = await sys_model.update(
      { id, key, name },
      {
        where: {
          id: id,
        },
      }
    );
    return ctx.success(res);
  },
  "POST /sys_model/del": async (ctx, next) => {
    let id = ctx.get("id");

    await autoFile.destroyApiFile(id);

    // 删除字段表
    await sys_model_field.destroy({ where: { model_id: id } });

    // 删除主数据
    const res = await sys_model.destroy({ where: { id: id } });

    return ctx.success(res);
  },
  // 生成model
  "POST /sys_model/regenerate": async (ctx, next) => {
    let row = ctx.getBody();
    let { id } = row;
    if (id) {
      let sysModelFields = await sys_model_field.findAll({ where: { model_id: id } });
      if (sysModelFields && sysModelFields.length > 0) {
        let tempUUid = uuid.v4();
        // 创建model
        await autoFile.autoModel(id, tempUUid);
        // 创建db
        await autoFile.autoDb(id, tempUUid);
        // 创建apiServer
        await autoFile.autoController(id);
      } else {
        return ctx.fail("字段未添加，无效生成");
      }
    }
    return ctx.success();
  },

  "POST /sys_model/table": async (ctx, next) => {
    let tableName = ctx.get("tableName");

    let isExistTableName = await querySql(`select TABLE_NAME from information_schema.TABLES where TABLE_NAME ="${tableName}"`);
    let tableColumns = await querySql(`SELECT COLUMN_KEY,COLUMN_TYPE,DATA_TYPE,COLUMN_NAME FROM information_schema.COLUMNS where TABLE_NAME ="${tableName}"`);
    let isExist = isExistTableName ? true : false;

    return ctx.success({ isExist, tableColumns });
  },
};
